﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using IIControls.Source;
using BusTransfer;
using GalaSoft.MvvmLight.Messaging;
namespace IIControls.IAControl
{
    /// <summary>
    /// UserControl1.xaml 的交互逻辑
    /// </summary>
    public partial class ValveControl : UserControl, IControls
    {

        private void valveinit()
        {       
            Elemnt_Init();       
            AddErrorString();
            AddToolTipString();
            Root_Leave();
            AddCmd();
            Detailtxt = Detail.Text;
            Idtxt = ID.Content.ToString();
            BindToolTip();
            StatusImg = PrintSatus.NORMAL;
        }

        #region 构造函数
        public ValveControl()
        {
            InitializeComponent();
            valveinit();
        }

        public ValveControl(Valve valve)
        {
            InitializeComponent();
            valveinit();
            Valveinit = valve;
           
        }



       

        private void AddErrorString()
        {
            ErrorMsg.Add("Valve_IDInputError", "编号长度最少3位,必须是数字，最后一位范围1-4");
            ErrorMsg.Add("Valve_DetailInputError", "说明不能为空或长度大于12个字符");
            ErrorMsg.Add("Valve_InputComplete", "输入正确的参数再保存");
        }

        private void AddToolTipString()
        {
            AddToolTipMsg("OpenValve", "开阀门");  //
            AddToolTipMsg("CloseValve", "关阀门");//
            AddToolTipMsg("CheckStatue", "检测状态");//
            AddToolTipMsg("Save", "保存配置");//
            AddToolTipMsg("Discard", "放弃保存");//
            AddToolTipMsg("S_Normal", "运行正常");//
            AddToolTipMsg("S_Failure", "通信失败");//
            AddToolTipMsg("S_StatusError", "状态不符合");//
            AddToolTipMsg("S_Wait", "数据发送成功，等待回复");
            AddToolTipMsg("ValveID", "阀门编号");//
            AddToolTipMsg("ValveTD", "阀门通道");//
            AddToolTipMsg("ValveInit", "初始化");//
            AddToolTipMsg("CheckVoltage", "检测电压");//
            AddToolTipMsg("ReadHistory", "阀门操作记录");//
            AddToolTipMsg("OpenValveTime", "开阀时间");//
            AddToolTipMsg("CloseValveTime", "关阀时间");//
            AddToolTipMsg("S_StatusCloseError", "检测结果:开");//
            AddToolTipMsg("S_StatusOpenError", "检测结果:关");//
        }

        private void BindToolTip()
        {
            DiscardTip.ToolTip = ToolMsg["Discard"];
            SaveTip .ToolTip = ToolMsg["Save"];
            History.ToolTip = ToolMsg["ReadHistory"];
            SetIdToolTip();
        }

        /// <summary>
        /// 设定编号上的tooltip
        /// </summary>
      public   void SetIdToolTip()
        {
            ID.ToolTip = (string)ToolMsg["ValveID"] + ":" + ((string)ID.Content).Substring(0, ((string)ID.Content).Length - 1) + " "
            + (string)ToolMsg["ValveTD"] + ":" + ((string)ID.Content).Substring(((string)ID.Content).Length - 1, 1);
        }

        public   List<SunValveControl > VolCollection = new List<SunValveControl>();

        void AddCmd()
        {
            VolCollection.Add(ADDVoltageValve(SunValveControl.CMDType.VALVE_OPEN, ToolMsg["OpenValve"]));
            VolCollection.Add(ADDVoltageValve(SunValveControl.CMDType.VALVE_CLOSE, ToolMsg["CloseValve"]));
            VolCollection.Add(ADDVoltageValve(SunValveControl.CMDType.VALVE_CHECKSTATUE, ToolMsg["CheckStatue"]));
            VolCollection.Add(ADDVoltageValve(SunValveControl.CMDType.VALVE_CHECKVOLTAGE, ToolMsg["CheckVoltage"]));
            VolCollection.Add(ADDVoltageValve(SunValveControl.CMDType.VALVE_INIT, ToolMsg["ValveInit"]));

            ValveOpen.Child = VolCollection.First (x=>x.ButtonType== SunValveControl.CMDType.VALVE_OPEN);
            ValveOpen.Child.Visibility = Visibility.Hidden;
            ValveClose .Child = VolCollection.First(x => x.ButtonType == SunValveControl.CMDType.VALVE_CLOSE );
            ValveClose.Child.Visibility  = Visibility.Hidden;
            ValveCheckStatue.Child = VolCollection.First(x => x.ButtonType == SunValveControl.CMDType.VALVE_CHECKSTATUE );
            ValveCheckStatue.Child.Visibility = Visibility.Hidden;
            ValveCheckVoltage.Child = VolCollection.First(x => x.ButtonType == SunValveControl.CMDType.VALVE_CHECKVOLTAGE );
            ValveCheckVoltage.Child.Visibility = Visibility.Hidden;
            ValveInit.Child = VolCollection.First(x => x.ButtonType == SunValveControl.CMDType.VALVE_INIT );
            ValveInit.Child.Visibility = Visibility.Hidden;
        }

        SunValveControl ADDVoltageValve(SunValveControl.CMDType type,string TTip)
        {
            SunValveControl.ButtonClickEvent VolsClick = new Source.SunValveControl.ButtonClickEvent(VolClick);
            return  new SunValveControl(type, VolsClick,TTip );
        }


        public SunValveControl SetButtonStatue(int cmd)
        {
            SunValveControl.CMDType scmd = (SunValveControl.CMDType)cmd;
            SunValveControl sv= VolCollection.First(x => x.ButtonType == (SunValveControl.CMDType)cmd);
            return  VolCollection.FirstOrDefault (x => x.ButtonType == (SunValveControl.CMDType)cmd);
            
        }
        #endregion

        #region 鼠标事件

        private void Root_MouseEnter(object sender, MouseEventArgs e)
        {
            this.RenderTransformOrigin = new Point(0.5, 0.5);
            ScaleTransform ST = new ScaleTransform();
            ST.ScaleX = 1.05;
            ST.ScaleY = 1.05;
            UserControlTransformGroup.Children.Add(ST);
            this.RenderTransform = UserControlTransformGroup;
           // border.Stroke  = new SolidColorBrush(Colors.AliceBlue );
            Root_Enter();
            ValveVoltage.Visibility = Visibility.Hidden;
        }

        private void Root_MouseLeave(object sender, MouseEventArgs e)
        {
            this.RenderTransformOrigin = new Point(0.5, 0.5);
            ScaleTransform ST = new ScaleTransform();
            ST.ScaleX = 1;
            ST.ScaleY = 1;
            UserControlTransformGroup.Children.Remove(UserControlTransformGroup.Children.LastOrDefault());
            UserControlTransformGroup.Children.Add(ST);
            this.RenderTransform = UserControlTransformGroup;
           // border.Stroke = new SolidColorBrush(Colors.Transparent  );
            Root_Leave();
            ValveVoltage.Visibility = Visibility.Visible;
        }
        #endregion

        #region 元素可见配置
        /// <summary>
        /// 控件初始化代码,初始值复制完毕后调用
        /// </summary>
       public  void Valve_Init()
        {
            Idtxt = ValveId;
            Detailtxt = ValveDetail;
        }

        void Elemnt_Init()
        {
            Discard.Visibility = Visibility.Hidden;
            Save.Visibility = Visibility.Hidden;
            History.Visibility = Visibility.Hidden;
        }


        List<SunValveControl >  GetVoltageValve()
        {
            List<SunValveControl> vols = new List<SunValveControl>();
            var linq = from UIElement e in VolButton.Children
                       where e is Viewbox
                       select e;
            foreach (Viewbox v in linq)
            {
                if (v.Child is SunValveControl)
                {
                    SunValveControl VV = (SunValveControl)v.Child;
                    vols.Add(VV);
                }
            }
            return vols;
        }

        void Root_Leave()
        {
           foreach(SunValveControl V in GetVoltageValve())
                    if (!V.ButtonIsEnable)
                        V.Visibility = Visibility.Hidden;
            History.Visibility = Visibility.Hidden;
        }


        void Root_Enter()
        {
            foreach (SunValveControl V in GetVoltageValve())
                    V.Visibility = Visibility.Visible ;
            History.Visibility = Visibility.Visible;
        }
        #endregion

        #region 鼠标进入、离开、按下事件
        SolidColorBrush EnterColor = new SolidColorBrush(Colors.LightBlue);
        SolidColorBrush LeaveColor = new SolidColorBrush(Colors.Transparent);
        double ZoomIn = 1.3;
        double ZoomOut = 1;
        private void  Element_ScaleTransform(UIElement UI, double Scalevalue)
        {
            UI.RenderTransformOrigin = new Point(0.5, 0.5);
            ScaleTransform ST = new ScaleTransform();
            ST.ScaleX = Scalevalue;
            ST.ScaleY = Scalevalue;
            UI.RenderTransform = ST;
        }

        private void Element_Enter(object obj)
        {
            UIElement UI = (UIElement)obj;
            Cursor = Cursors.Hand;
            Element_ScaleTransform(UI, ZoomIn);
        }

        private void Element_Leave(object obj)
        {
            UIElement UI = (UIElement)obj;
            Cursor = Cursors.Arrow;
            Element_ScaleTransform(UI, ZoomOut);
        }

        private void Mouse_Enter(object sender, MouseEventArgs e)
        {
            Element_Enter(sender);
        }

        private void Mouse_Leave(object sender, MouseEventArgs e)
        {
            Element_Leave(sender);
        }


        private void History_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            CT = ClickType.ValveReadHistory ;
        
            Storyboard RH = (Storyboard)user.Resources["RootHidden"];
            RH.Begin();
            Storyboard RV = (Storyboard)user.Resources["RecordVisual"];
            RV.Begin();
            Panel.SetZIndex(Root, -1);
            Panel.SetZIndex(Record, 0);
            MsgTransfer.Instance.Send(new NotificationMessage<ValveControl>( CT ,this,"v_config"));
            //Root.Visibility = Visibility.Hidden;
            //Record.Visibility = Visibility.Visible;
        }



        #endregion

        #region 文本框处理
        string Idtxt = "";
        private void ID_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TextBox WriteId = new TextBox();
            WriteId.Text = (string)ID.Content;
            //Idtxt = WriteId.Text;
            BH.Child = WriteId;
            WriteId.LostFocus += WriteId_LostFocus;
            WriteId.KeyUp += WriteId_KeyUp;
            WriteId.TextChanged += Txt_TextChanged;
            WriteId.Focus();
            WriteId.SelectAll();

        }

        private void WriteId_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                WriteIdLost(((TextBox)sender).Text);
        }

        private void WriteId_LostFocus(object sender, RoutedEventArgs e)
        {
            WriteIdLost(((TextBox)sender).Text);
        }

        private void WriteIdLost(string txt)
        {
            try
            {
                ValveId = txt;
                BH.Child = ID;
            }
            catch 
            {
                MessageBox.Show(ErrorMsg["Valve_IDInputError"]);
            }
            
        }

        

        string Detailtxt = "";
        private void Detil_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            TextBlock  Detail = (TextBlock)sender;
            TextBox WriteDetail = new TextBox();
            WriteDetail.Text = (string)Detail.Text ;
            //Detailtxt = WriteDetail.Text;
            SM.Child= WriteDetail;
            WriteDetail.LostFocus += WriteDetail_LostFocus;
            WriteDetail.KeyUp += WriteDetail_KeyUp;
            WriteDetail.TextChanged += Txt_TextChanged;
            WriteDetail.Focus();
            WriteDetail.SelectAll();
        }

        private void Txt_TextChanged(object sender, TextChangedEventArgs e)
        {
            Save.Visibility = Visibility.Visible;
            Discard.Visibility = Visibility.Visible;
        }

        private void WriteDetail_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.Key == Key.Enter)
                WriteDetailLost(sender);
        }

        private void WriteDetail_LostFocus(object sender, RoutedEventArgs e)
        {
            WriteDetailLost(sender);
        }

        private void WriteDetailLost(object sender)
        {
            WriteDetailLostTxt(((TextBox)sender).Text);
        }

        private void WriteDetailLostTxt(string txt)
        {
            try
            {
                ValveDetail = txt;
                SM.Child= Detail;
            }
            catch (Exception ex)
            {
                string a = ex.Message;
                MessageBox.Show(ErrorMsg["Valve_DetailInputError"]);
            }
            
        }

        private void Discard_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {

            if (Detailtxt != "")
            {
                SM.Child .LostFocus -= WriteDetail_LostFocus;
                WriteDetailLostTxt(Detailtxt);
            }
            if (Idtxt != "")
            {
                BH.Child.LostFocus -= WriteId_LostFocus;
                WriteIdLost(Idtxt);

            }
            Save.Visibility = Visibility.Hidden;
            Discard.Visibility = Visibility.Hidden;
            CT = ClickType.ValveDisCard;
        
        }

        private void Save_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Saveid();

        }


        private void Saveid()
        {
            if (SM.Child.GetType() == typeof(TextBox) || BH.Child.GetType() == typeof(TextBox))
            {
                MessageBox.Show(ErrorMsg["Valve_InputComplete"]);
                return;
            }
            Save.Visibility = Visibility.Hidden;
            Discard.Visibility = Visibility.Hidden;
            
            ValveId = (string)ID.Content;
            ValveDetail = (string)Detail.Text;
            Idtxt = ValveId;
            Detailtxt = ValveDetail;
            SetIdToolTip();
            CT = ClickType.ValveSave;
            MsgTransfer.Instance.Send(new NotificationMessage<ValveControl>(CT, this, "v_config"));
        }
        #endregion

        #region 字典字段    
        Dictionary<string, string> ErrorMsg = new Dictionary<string, string>();
        /// <summary>
        /// <para>添加错误说明</para> 
        ///<para>"Valve_IDInputError", "编号长度最少5位"</para>
        ///<para>"Valve_DetailInputError", "说明不能为空"</para> 
        ///<para>"Valve_InputComplete", "输入正确的参数再保存"</para>
        /// </summary>
        /// <param name="key"></param>
        /// <param name="value"></param>
        public void AddErrorMsg(string key, string value)
        {
            if (ErrorMsg.ContainsKey(key))
                ErrorMsg[key] = value;
            else
                ErrorMsg.Add(key, value);
        }

        Dictionary<string, string> ToolMsg = new Dictionary<string, string>();
        /// <summary>
        /// 气泡内容
        /// </summary>
        /// <param name="key">传入的key值</param>
        /// <param name="value">传入的值</param>
        public void AddToolTipMsg(string key,string value)
        {
            if (ToolMsg.ContainsKey(key))
                ToolMsg[key] = value;
            else
                ToolMsg.Add(key, value);
        }
        #endregion 

        #region 依赖项属性,绑定界面值使用
        /// <summary>
        /// 阀门倾斜角度
        /// </summary>
        public double angle
        {
            get { return (double)GetValue(angleProperty); }
            set { SetValue(angleProperty, value); }
        }

        // Using a DependencyProperty as the backing store for angle.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty angleProperty =
            DependencyProperty.Register("angle", typeof(double), typeof(ValveControl), new PropertyMetadata(0.0),new ValidateValueCallback (AngleCheck));

        static bool AngleCheck(object value)
        {
            if (value.GetType() == typeof(double))
                return true;
            else
                return false;
        }

        ///// <summary>
        ///// 阀门编号
        ///// </summary>
        //public string ValveId  { get; set; }

        /// <summary>
        /// 阀门编号
        /// </summary>
        public string ValveId
        {
            get { return (string)GetValue(ValveIdProperty); }
            set {
                SetValue(ValveIdProperty, value);
                messReg();
            }
        }

        // Using a DependencyProperty as the backing store for ValveId.  This enables animation, styling, binding, etc...
        PropertyMetadata PM = new PropertyMetadata();
        
        public static readonly DependencyProperty ValveIdProperty =
            DependencyProperty.Register("ValveId", typeof(string), typeof(ValveControl), new PropertyMetadata("09655351",new PropertyChangedCallback (IdChange) ),new ValidateValueCallback(IDCheck));

        private static void IdChange(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
                IDPRO = new string[2] { (string)e.OldValue, (string)e.NewValue };       
    }

        /// <summary>
        /// 记录ID变化
        /// IDPRO[0]=oldvalue
        /// IDPRO[1]=newvalue
        /// </summary>
        static string[] IDPRO { get; set; }

        static  bool  IDCheck(object value)
        {
            string RES = (string )value;
            if (RES.Length == 0 || RES.Length < 4 || !isNumberic(RES )  || !isBindNo(RES))
                return false;
            else
                return true;
                
        }

        static  bool isNumberic(string message)
        {
            System.Text.RegularExpressions.Regex rex =
            new System.Text.RegularExpressions.Regex(@"^\d+$");
            if (rex.IsMatch(message))
                return true;
            else
                return false;
        }

        static bool isBindNo(string RES)
        {
            int a = int.Parse(RES.Substring(RES.Length - 1, 1));
            if (a < 1 || a > 4)
                return false;
            else
                return true;

        }


        /// <summary>
        /// 阀门说明
        /// </summary>
        public string ValveDetail
        {
            get { return (string)GetValue(ValveDetailProperty); }
            set { SetValue(ValveDetailProperty, value); }
        }

        // Using a DependencyProperty as the backing store for ValveDetail.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty ValveDetailProperty =
            DependencyProperty.Register("ValveDetail", typeof(string), typeof(ValveControl), new PropertyMetadata("详情"),new ValidateValueCallback(DetailCheck));

        static bool DetailCheck(object value)
        {
            string v = (string)value;
            if (v.Length == 0 || v == "" )
                return false;
            else
                return true;
        }




        public string StartTime
        {
            get { return (string)GetValue(StartTimeProperty); }
            set { SetValue(StartTimeProperty, value); }
        }

        // Using a DependencyProperty as the backing store for StartTime.  This enables animation, styling, binding, etc...
        public static readonly DependencyProperty StartTimeProperty =
            DependencyProperty.Register("StartTime", typeof(string), typeof(ValveControl), new PropertyMetadata(""));




        #endregion

        #region 一般属性

        private Valve initprop;
        /// <summary>
        /// 阀门初始化
        /// </summary>
        public Valve Valveinit
        {
            get { return initprop; }
            set
            {
                initprop = value;
                //ValveId =Convert.ToInt32( initprop.Number).ToString("00000")+initprop.Type.ToString();
                ValveId = initprop.Number+ initprop.Type.ToString();
                ValveDetail = initprop.Name;
                if (initprop.State == 0)
                    SetValveCallBack(ValveState.OPEN);
                else if (initprop.State == 1)
                    SetValveCallBack(ValveState.CLOSE);
                BindToolTip();
            }
        }


        /// <summary>
        /// 阀门绑定编号（控制器上阀门几）
        /// </summary>
        public string SunValveNo
        {
            get
            {
                return ValveId.Substring(ValveId.Length-1,1);
            }
        }


        private CMDPress opertype;
        /// <summary>
        /// 按下按钮类型
        /// </summary>
        public CMDPress OperType
        {
            get { return opertype; }
            set
            {
                opertype = value;
                SetTime(opertype);
            }
        }

        private void SetTime(CMDPress cmd)
        {
            if (CmdClickTime.ContainsKey(cmd))
                CmdClickTime[cmd] = DateTime.Now;
            else
                CmdClickTime.Add(cmd, DateTime.Now);
        }

        private DateTime  GetTime(CMDPress cmd)
        {
            if (CmdClickTime.ContainsKey(cmd))
                return CmdClickTime[cmd];
            else
            {
                CmdClickTime.Add(cmd, DateTime.Now);
                return CmdClickTime[cmd];
            }
        }

        /// <summary>
        /// 记录按下时间
        /// </summary>
        Dictionary<CMDPress, DateTime> CmdClickTime = new Dictionary<CMDPress, DateTime>();

        /// <summary>
        /// 功能按钮是否按下
        /// </summary>
       [Flags]
       public  enum CMDPress
        {
            None = 0,
            /// <summary>
            /// 开阀门按钮是否按下
            /// </summary>
            OpenValve = 0x01,
            /// <summary>
            /// 关阀门按钮是否按下
            /// </summary>
            CloseValve = 0x02,
            /// <summary>
            /// 检测状态按钮是否按下
            /// </summary>
            CheckStatue=0x04,
            /// <summary>
            /// 检测电压按钮是否按下
            /// </summary>
            CheckVol=0x08,
            /// <summary>
            /// 初始化按钮是否按下
            /// </summary>
            Init=0x10

        }


        private double voltage;
        /// <summary>
        /// 电池电压
        /// </summary>
        public double Voltage
        {
            get { return voltage; }
            set
            {
                //保留2位小数
                voltage =Math.Round( value,2);
                if (voltage > 0)
                    ValveVoltage.Content = voltage.ToString() + "V";
                else
                    ValveVoltage.Content = "";
            }
        }


        /// <summary>
        /// 按键类型
        /// </summary>
        public ClickType CT { get; set; }

        /// <summary>
        /// 状态值
        /// </summary>
        public enum PrintSatus
        {
            /// <summary>
            /// 等待数据回复
            /// </summary>
            WAITCALLBACK,
            /// <summary>
            /// 通信失败
            /// </summary>
            FAILURE,
            /// <summary>
            /// 状态错误
            /// </summary>
            STATUSERROR,
            /// <summary>
            /// 状态正常
            /// </summary>
            NORMAL
        }




        private PrintSatus statusimg= PrintSatus.NORMAL ;
        /// <summary>
        /// 根据状态值显示不同图标
        /// </summary>
        public PrintSatus StatusImg
        {
            get { return statusimg; }
            set
            {
                statusimg = value;
                switch (statusimg)
                {
                    case PrintSatus.NORMAL:
                        IIControls.Source.NormalControl NC = new Source.NormalControl();
                        NC.ToolTipString =(string)ToolMsg ["S_Normal"];
                        StatusIco.Child = NC;
                        break;
                    case PrintSatus.FAILURE:
                        IIControls.Source.ERRORControl EC = new Source.ERRORControl();
                        EC.ToolTipString = (string)ToolMsg["S_Failure"];
                        StatusIco.Child = EC;
                        break;
                    case PrintSatus.STATUSERROR:
                        IIControls.Source.StatueAlarmControl SA = new Source.StatueAlarmControl();
                        SA.ToolTipString = (string)ToolMsg["S_StatusError"];
                        StatusIco.Child = SA;
                        break;
                    case PrintSatus.WAITCALLBACK:
                        IIControls.Source.WaitBack WB = new Source.WaitBack();
                        WB.ToolTipString = (string)ToolMsg["S_Wait"];
                        StatusIco.Child = WB;
                        break;

                }
            }
        }


        private DataTable history;
        /// <summary>
        ///<para>历史记录，表头如下</para> 
        ///<para>时间   ， 操作（开或关）， 累计时长</para>
        /// </summary>
        public DataTable HisTory
        {
            get { return history; }
            set {
                history = value;
                ValveRecord.ItemsSource = history.DefaultView;
            }
        }

        /// <summary>
        /// 阀门操作时间
        /// </summary>
        public DateTime OperTime { get; set; }

        /// <summary>
        /// 阀门是否打开
        /// </summary>
        public bool SunValveIsOpen { get; set; }

        public  enum ValveState
        {
        
          /// <summary>
          /// 阀门关
          /// </summary>
          CLOSE,
            /// <summary>
            /// 阀门开
            /// </summary>
            OPEN,
            /// <summary>
            /// 检测状态
            /// </summary>
            STATUE,
          /// <summary>
          /// 检测电压
          /// </summary>
          VOLTAGE,
          /// <summary>
          /// 初始化
          /// </summary>
            INIT,
            /// <summary>
            /// 通信失败
            /// </summary>
            ERROR,


        }

        SolidColorBrush OpenColor = new SolidColorBrush(Color.FromArgb(0xFF, 0x50, 0xA8, 0xB4)); 
        SolidColorBrush CloseColor = new SolidColorBrush(Color.FromArgb(0xFF, 0xD2, 0x9B, 0xB4));
        SolidColorBrush UnKnowColor = new SolidColorBrush(Color.FromArgb(0xFF, 0x95, 0xA8, 0xB2));
        SolidColorBrush ErrorColor = new SolidColorBrush(Color.FromArgb(0xFF, 0x95, 0xA8, 0xB2));// new SolidColorBrush(Color.FromArgb(0xFF, 0x72, 0x99, 0x97));



        /// <summary>
        /// <para>设置控件状态，共5种状态,obj对应类型如下</para>
        /// <para>ValveState.OPEN->null,ValveState.CLOSE->null,ValveState.STATUE->bool:打开true，关闭false</para>
        /// <para>ValveState.VOLTAGE->double：电压值,ValveState.ERROR->null</para>
        /// </summary>
        /// <param name="S"></param>
        /// <param name="obj"></param>
        /// <returns></returns>
        public bool  SetValveCallBack(ValveState S,object obj=null )
        {
            //try
            //{    
            switch(S)
            {
                case ValveState.OPEN:
                    border.Fill = OpenColor;
                        halfborder.Fill = OpenColor;
                    StatusImg = PrintSatus.NORMAL;
                    OperTime = DateTime.Now;
                    StartTime = DateTime.Now.ToString();
                    Timers.ToolTip = ToolMsg["OpenValveTime"];
                    user.ToolTip = ToolMsg["OpenValve"];
                    SunValveIsOpen = true;
                    initprop.State =1;
                    break;
                case ValveState.CLOSE:
                        border.Fill = CloseColor;
                        halfborder.Fill = CloseColor ;
                        StatusImg = PrintSatus.NORMAL;
                    OperTime = DateTime.Now;
                    StartTime = DateTime.Now.ToString();
                    Timers.ToolTip = ToolMsg["CloseValveTime"];
                    user.ToolTip = ToolMsg["CloseValve"];
                    SunValveIsOpen = false ;
                    initprop.State = 0;
                    break;
                case ValveState.STATUE:
                        if (obj == null || obj.GetType() != typeof(bool   ))
                            return false;
                        bool b = (bool)obj;
                        if (b != SunValveIsOpen)
                    {
                        if (SunValveIsOpen==true )
                        {
                            StartTime = ToolMsg["S_StatusOpenError"];
                            Timers.ToolTip = ToolMsg["S_StatusOpenError"];
                            halfborder.Fill = OpenColor;
                        }
                        else
                        {
                            StartTime = ToolMsg["S_StatusCloseError"];
                            Timers.ToolTip = ToolMsg["S_StatusCloseError"];
                            halfborder.Fill = CloseColor;
                        }
                        user.ToolTip = ToolMsg["S_StatusError"];
                        border.Fill = UnKnowColor;
                        StatusImg = PrintSatus.STATUSERROR;
                    }
                    else
                        StatusImg = PrintSatus.NORMAL;
                    break;

                case ValveState.VOLTAGE:
                        if (obj == null || obj.GetType() != typeof(double ))
                            return false;
                        Voltage = (double)obj;
                    StatusImg = PrintSatus.NORMAL;
                    break;
                case ValveState.ERROR:
                    border.Fill = ErrorColor;
                        halfborder.Fill  = ErrorColor;
                    StatusImg = PrintSatus.FAILURE;
                    StartTime = ToolMsg["S_Failure"];
                    Timers.ToolTip = ToolMsg["S_Failure"];
                    user.ToolTip = ToolMsg["S_Failure"];
                    break;
                case ValveState.INIT:
                    StatusImg = PrintSatus.NORMAL;
                    break;
            }
                return true;
            //}
            //catch (Exception ex)
            //{
            //    return false;
            //}
        }

        #endregion


        #region 委托事件





       public  void VolClick(SunValveControl VV)
        {
            CT = ClickType.None;
            switch (   VV.ButtonType )
            {
                case SunValveControl.CMDType.VALVE_OPEN:
                    if (VV.ButtonIsEnable)
                    {
                        OperType |= CMDPress.OpenValve;
                        CT = ClickType.ValveOpen;
                        AddOper(ClickType.ValveOpen);
                        
                    }
                    else
                    {
                        OperType &= ~CMDPress.OpenValve;
                        DeleteOper(ClickType.ValveOpen);
                    }
             
                    break;
                case SunValveControl.CMDType.VALVE_CLOSE :
                    if (VV.ButtonIsEnable)
                    {
                        OperType |= CMDPress.CloseValve;
                        CT = ClickType.ValveClose;
                        AddOper(ClickType.ValveClose);
                    }
                    else
                    {
                        OperType &= ~CMDPress.CloseValve;
                        DeleteOper(ClickType.ValveClose);
                    }
              
                    break;
                case SunValveControl.CMDType.VALVE_CHECKSTATUE :
                    if (VV.ButtonIsEnable)
                    {
                        OperType |= CMDPress.CheckStatue;
                        CT = ClickType.ValveCheckeStatue;
                        AddOper(ClickType.ValveCheckeStatue);
                    }
                    else
                    {
                        OperType &= ~CMDPress.CheckStatue;
                        DeleteOper(ClickType.ValveCheckeStatue);
                    }
                
                    break;
                case SunValveControl.CMDType.VALVE_CHECKVOLTAGE   :
                    if (VV.ButtonIsEnable)
                    {
                        OperType |= CMDPress.CheckVol;
                        CT = ClickType.ValveCheckeVoltage;
                        AddOper(ClickType.ValveCheckeVoltage);
                    }
                    else
                    {
                        OperType &= ~CMDPress.CheckVol;
                        DeleteOper(ClickType.ValveCheckeVoltage);
                    }
                 
                    break;
                case SunValveControl.CMDType.VALVE_INIT  :
                    if (VV.ButtonIsEnable)
                    {
                        OperType |= CMDPress.Init;
                        CT = ClickType.ValveInit;
                        AddOper(ClickType.ValveInit);
                    }
                    else
                    {
                        OperType &= ~CMDPress.Init;
                        DeleteOper(ClickType.ValveInit);
                    }
        
                    break;
            }
            
        }

        #region 开关阀门、检测状态


        /// <summary>
        /// 操作类型
        /// </summary>
        public enum ClickType
        {
            /// <summary>
            /// 什么也没按下
            /// </summary>
            None=0,
            /// <summary>
            /// 开阀门
            /// </summary>
            ValveOpen,
            /// <summary>
            /// 关阀门
            /// </summary>
            ValveClose,
            /// <summary>
            /// 检测状态
            /// </summary>
            ValveCheckeStatue,
            /// <summary>
            /// 读取历史
            /// </summary>
            ValveReadHistory,
            /// <summary>
            /// 保存配置
            /// </summary>
            ValveSave,
            /// <summary>
            /// 放弃配置
            /// </summary>
            ValveDisCard,
            /// <summary>
            /// 检测电压
            /// </summary>
            ValveCheckeVoltage,
            /// <summary>
            /// 初始化
            /// </summary>
            ValveInit,
            /// <summary>
            /// 从外部读取操作历史
            /// </summary>
            ValveReadExtHistory


        }





        #endregion

        #endregion

        private void exit_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            Storyboard RV = (Storyboard)user.Resources["RootVisual"];
            RV.Begin();
            Storyboard RH = (Storyboard)user.Resources["RecordHidden"];
            RH.Begin();
            Panel.SetZIndex(Record , -1);
            Panel.SetZIndex(Root, 1);

        }

        private void Label_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            CT = ClickType.ValveReadExtHistory ;
        }

        #region 接口实现
        int IControls.GetType()
        {
            return 0;
        }

        List<TaskMsg> list_TM = new List<TaskMsg>();

        public List<TaskMsg> GetCmd()
        {
            return list_TM;
        } 


        /// <summary>
        /// 添加一个操作
        /// </summary>
        /// <param name="CTs"></param>
        void AddOper(ClickType  CTs)
        {
            //如果已经存在就移除
            DeleteOper(CTs);
             TaskMsg tm = new TaskMsg();
            tm.CmdType = (int)CTs;
            tm.DeviceType = 0;
            tm.OperTime = DateTime.Now;
            tm.DeviceAllMsg = this;
            tm.DeviceId = ValveId;
            list_TM.Add(tm);
            MsgTransfer.Instance.Send(tm, "v_addtask");
        }

        /// <summary>
        /// 删除一个操作
        /// </summary>
        /// <param name="CT"></param>
        void DeleteOper(ClickType CT)
        {
            try
            {
                //存在就移除
                TaskMsg tm = list_TM.Where(x => x.CmdType == (int)CT).First();
                list_TM.Remove(tm);
                MsgTransfer.Instance.Send(tm, "v_deltask");
            }
            catch (Exception)
            {
               //不存在则出错
            }

        }
        #endregion


        #region mvvmlight中的messenger
        /// <summary>
        /// 注册事件
        /// </summary>
        public  void messReg()
        {
            if (IDPRO != null)
            {
                //先移除所有注册防止重复注册
                UnReg();
                //注册按钮事件
                MsgTransfer.Instance.Register<object>(this, "v_" + Valveinit.GPRSNumber+ IDPRO[1], SetButton);
                //注册改变控件状态事件
                MsgTransfer.Instance.Register<object[]>(this, "v_" + Valveinit.GPRSNumber + IDPRO[1], SetParams);
            }
        }

        /// <summary>
        /// 解除注册事件
        /// </summary>
        public void UnReg()
        {
            if (IDPRO != null)
            {
                //注册按钮事件
                MsgTransfer.Instance.Unregister<object>(this, "v_" + Valveinit.GPRSNumber + IDPRO[0], SetButton);
                //注册改变控件状态事件
                MsgTransfer.Instance.Unregister<object[]>(this, "v_" + Valveinit.GPRSNumber + IDPRO[0], SetParams);
            }
        }

        /// <summary>
        /// <para>设置状态,object[]必须是2维数组，object[0]操作类型，object[1]对应类型传入值</para>
        /// <para>状态OPEN,CLOSE.ERROR，object[1]可以为null</para> 
        /// <para>状态STATUE，object[1]=bool；状态VOLTAGE，object[1]=double；</para>
        /// </summary>
        /// <param name="notify"></param>
        private void SetParams(object[] notify)
        {
            Dispatcher.Invoke(() =>
            {
                object[] obj = notify;
                if (obj == null || obj.Length != 2 || obj[0].GetType() != typeof(ValveState))
                    return;
                switch ((ValveState)obj[0])
                {
                    case ValveState.OPEN:
                        SetValveCallBack(ValveState.OPEN);
                        break;
                    case ValveState.CLOSE:
                        SetValveCallBack(ValveState.CLOSE);
                        break;
                    case ValveState.STATUE:
                        if (obj[1].GetType() == typeof(bool))
                            SetValveCallBack(ValveState.STATUE, (bool)obj[1]);
                        break;
                    case ValveState.ERROR:
                        SetValveCallBack(ValveState.ERROR);
                        break;
                    case ValveState.VOLTAGE:
                        if (obj[1].GetType() == typeof(double))
                            SetValveCallBack(ValveState.VOLTAGE, (double)obj[1]);
                        break;
                    case ValveState.INIT:
                        SetValveCallBack(ValveState.INIT, null);
                        break;
                }
            });
        }

        private void SetButton(object obj)
        {
            Dispatcher.Invoke(new Action(() =>
            {

                if (obj != null && obj.GetType() == typeof(ClickType) )
                {
                    ClickType ct = (ClickType)obj;
                    SunValveControl.CMDType cmd = SunValveControl.CMDType.NONE;
                    switch (ct)
                    {
                        case ClickType.ValveOpen:
                            cmd = SunValveControl.CMDType.VALVE_OPEN;
                            Root_Enter();
                            break;
                        case ClickType.ValveClose:
                            cmd = SunValveControl.CMDType.VALVE_CLOSE;
                            break;
                        case ClickType.ValveCheckeStatue:
                            cmd = SunValveControl.CMDType.VALVE_CHECKSTATUE;

                            break;
                        case ClickType.ValveCheckeVoltage:
                            cmd = SunValveControl.CMDType.VALVE_CHECKVOLTAGE;
                            break;
                        case ClickType.ValveInit:
                            cmd = SunValveControl.CMDType.VALVE_INIT;
                            break;
                    }
                    if (cmd != SunValveControl.CMDType.NONE)
                    {
                        SunValveControl sc = VolCollection.First(x => x.ButtonType == cmd);
                        if (sc != null)
                            sc.click();
                        Root_Leave();
                    }
                }


            }));
        }

    
        }




        #endregion


    }
